package com.zhangyj.util;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class GeneralTree<T> {
	private List<GeneralTree<T>> childs = null;

	private T item;

	private GeneralTree<T> parent;

	private int height = 0;

	public GeneralTree(T item) {
		this.setValue(item);
	}

	public GeneralTree() {
		this(null);
	}

	public void setValue(T item) {
		this.item = item;
	}

	public T getValue() {
		return item;
	}

	private void addHeight() {
		this.height++;
		if (this.parent != null) {
			if (this.parent.height <= this.height) {
				this.parent.height = this.height;
			}
			this.parent.addHeight();
		}
	}

	private void calculateHeight(GeneralTree<T> tree) {
		if (childs == null) {
			this.childs = new ArrayList<GeneralTree<T>>();
			if (tree.height >= this.height)
				this.height = tree.height;
			this.addHeight();
		} else if (tree.height >= this.height) {
			this.height = tree.height;
			this.addHeight();
		}
	}

	public void add(GeneralTree<T> tree) {
		this.add(tree, false);
	}

	public void add(GeneralTree<T> tree, boolean isCalculateHeight) {
		if (isCalculateHeight)
			calculateHeight(tree);
		tree.parent = this;
		if (this.childs == null) {
			this.childs = new ArrayList<GeneralTree<T>>();
		}
		this.childs.add(tree);
	}

	public boolean hasChilds() {
		return this.childs != null;
	}

	public GeneralTree<T> getChild(T item) {
		if (!this.hasChilds()) {
			return null;
		}
		GeneralTree<T> tree = null;

		Iterator<GeneralTree<T>> iterator = this.childs.iterator();
		while (iterator.hasNext()) {
			GeneralTree<T> elem = (GeneralTree<T>) iterator.next();
			if (elem.equals(item)) {
				tree = elem;
				break;
			}
		}
		return tree;
	}

	public List<GeneralTree<T>> getChilds() {
		return this.childs;
	}

	public int getWidth() {
		if (childs == null) {
			return 0;
		}
		return this.childs.size();
	}

	public int getHeight() {
		return this.height;
	}

	public GeneralTree<T> getParent() {
		return parent;
	}

	public static void main(String arg[]) {
		GeneralTree<String> t = new GeneralTree<String>();
		GeneralTree<String> t1 = new GeneralTree<String>("A");
		GeneralTree<String> t2 = new GeneralTree<String>("b");
		GeneralTree<String> t3 = new GeneralTree<String>("c");
		GeneralTree<String> t4 = new GeneralTree<String>("d");
		t1.add(t2);
		t2.add(t3);
		t.add(t1);
		t.add(t4);
		System.out.println(t.height);
		System.out.println(t1.height);
		System.out.println(t2.height);
		System.out.println(t3.height);
		System.out.println(t4.height);

	}
}

